home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 8301 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.8 KB

  1. Path: fas-news.harvard.edu!course2!martino
  2. From: martino@course2.harvard.edu (Carlo Martino)
  3. Newsgroups: comp.lang.c
  4. Subject: [Q] functions returning structures
  5. Date: 3 Mar 1996 01:28:19 GMT
  6. Organization: Harvard University, Cambridge, Massachusetts
  7. Message-ID: <4hasjj$opf@decaxp.harvard.edu>
  8. NNTP-Posting-Host: course2.harvard.edu
  9. X-Newsreader: TIN [version 1.2 PL2]
  10.  
  11. Is it bad for a function to return a structure?  I have been programming in
  12. C for upwards of 6 years, and only recently did I hear something to the effect
  13. that structures returned by functions have a tendency to be corrupted.
  14.  
  15. Then, today, it actually happened to me.,,,
  16.  
  17. I am using a structure defined in my header as:
  18.  
  19.     typedef struct rgb
  20.         {
  21.         unsigned char           r;
  22.         unsigned char           g;
  23.         unsigned char           b;
  24.         } RGB;
  25.  
  26. "get_color()" was declared in my header as:
  27.  
  28.     RGB    get_color(      VECTOR          position );
  29.  
  30. And I'd call it like so:
  31.  
  32.     new_color = get_color( new_position );
  33.  
  34. This work fine in SunOS.  But when I ported this morning to HP-UX, the
  35. value assigned to "new_color" was always screwy.  I walked through it
  36. in gdb, and the values within "get_color" were precisely what they ought
  37. to be; it was only the returned structure that was mess up.
  38.  
  39. So I changed things:
  40.  
  41.     RGB*    get_color(      VECTOR          position );
  42.  
  43. Which requires an extra free after I'm done with the values referenced by
  44. the returned pointer.  Not to mention the fact that screwing around with
  45. the pointers, when all I real want is the values, is considerably less
  46. elegant.
  47.  
  48. What was going wrong?  Is there a way to return structures without putting
  49. them on the heap?  When am I at risk for structures to become corrupt and
  50. when am I OK?
  51.  
  52. Needless to say, any enlightenment would be greatly appreciated.
  53.  
  54. Thanking you in advance,
  55.  
  56.     Carlo Martino
  57.  
  58.  
  59.